package org.eclipse.wtp.sample.flashcards;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LookupServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// make sure we can get special characters
		if (request.getCharacterEncoding() == null)
			request.setCharacterEncoding("UTF-8");
		
		// get reference to FlashCardSet
		FlashCardSet localSet = (FlashCardSet)request.getSession().getAttribute("flashcardset");
		
		// get data from form
		String whichkey = request.getParameter("whichkey");
		String entry = request.getParameter("entry");
		String returnvalue = "";
		
		// search for key in FlashCardSet
		if (whichkey.equals("key1")) {
			String answer = localSet.lookupByKey1(entry);

			// post response to session
			if (!answer.equals("")) {
				returnvalue = entry + " matches " + answer;
			}
			else {
				returnvalue = "no match found for: " + entry;
			}
			request.getSession().setAttribute("response1", returnvalue );
		}
		else if (whichkey.equals("key2")) {
			String answer = localSet.lookupByKey2(entry);

			// post response to session
			if (!answer.equals("")) {
				returnvalue = entry + " matches " + answer;
			}
			else {
				returnvalue = "no match found for: " + entry;
			}
			request.getSession().setAttribute("response2", returnvalue );
		}
		else {
			returnvalue = "Error: bad key";
			request.getSession().setAttribute("response1", returnvalue );
			request.getSession().setAttribute("response2", returnvalue );
		}

		
		// forward back to lookup.jsp
		getServletContext().getRequestDispatcher("/lookup.jsp").forward(request, response);

	}

}
